<template>
  <!-- 该组件是新增一条app数据 -->
  <div>
    <a-modal
      :title="titleMap"
      :width="550"
      :visible="visible"
      :confirm-loading="confirmLoading"
      @cancel="handleCancel"
    >
      <a-form
        :form="form"
        :label-col="{ span: 5 }"
        :wrapper-col="{ span: 19 }"
        layout="horizontal"
      >
        <!-- 风险来源 -->
        <a-form-item :label="$t('user.required111566126')">
          <a-radio-group
            name="radioGroup"
            v-model="ifflag"
            v-decorator="[
              'appSource',
              {
                rules: [
                  {
                    required: true,
                    message: $t('user.verification-code.required11156679'),
                  },
                ],
              },
            ]"
            :disabled="mode === 3"
          >
            <a-radio :value="1"> enterprise </a-radio>
            <a-radio :value="2"> non-enterprise </a-radio>
          </a-radio-group>
        </a-form-item>
        <!-- app类型 -->
        <a-form-item :label="$t('user.required111566127')">
          <a-select
            :placeholder="$t('user.verification-code.required11156612711')"
            v-decorator="[
              'appType',
              {
                rules: [
                  {
                    required: true,
                    message: $t('user.verification-code.required11156612711'),
                  },
                ],
              },
            ]"
            :disabled="mode === 3"
          >
            <a-select-option value="1">
              {{ $t("menu.account.setting.app") }}
            </a-select-option>
            <a-select-option value="2">
              {{ $t("menu.account.setting.other") }}
            </a-select-option>
            <a-select-option value="3">
              {{ $t("menu.account.setting.offline") }}
            </a-select-option>
          </a-select>
        </a-form-item>

        <!-- app名称 -->
        <a-form-item :label="$t('menu.list.search-list.projects')">
          <a-input
            v-decorator="[
              'appName',
              {
                rules: [
                  {
                    required: true,
                    message: $t(
                      'user.verification-code.required111566110577212'
                    ),
                  },
                ],
              },
            ]"
            :placeholder="$t('menu.list.search-list.applications')"
            :disabled="mode === 3"
          />
        </a-form-item>
        <!-- app联系人 -->
        <a-form-item
          :label="$t('menu.profile')"
          :colon="false"
          labelAlgin="left"
        >
          <a-select
            :placeholder="$t('menu.profile.basic')"
            allowClear
            v-decorator="[
              'appOwner',
              {
                rules: [
                  {
                    required: true,
                    message: $t(
                      'user.verification-code.required111566110577213'
                    ),
                  },
                ],
              },
            ]"
            option-filter-prop="children"
            :disabled="disabled || mode === 3"
            :filterOption="false"
            show-search
            :default-active-first-option="false"
            v-model="inputValue"
            @search="filte1rOption"
            @select="ownerChange"
          >
            <a-select-option
              v-for="item in userList"
              :value="item.label"
              :key="item.value"
            >
              {{ item.label }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <!-- app部门 -->
        <a-form-item
          :label="$t('menu.profile.advanced')"
          :colon="false"
          labelAlgin="left"
        >
          <a-input
            :placeholder="$t('user.login.message-invalid-credentials')"
            v-decorator="[
              'appDepartment',
              {
                rules: [
                  {
                    required: true,
                    message: $t('user.login.message-invalid-credentials'),
                  },
                ],
              },
            ]"
            :disabled="mode === 3"
          />
        </a-form-item>
        <!-- 套壳，里面的内容一次判断 -->
        <div v-if="ifflag == 1">
          <a-form-item label="enterprise APP ID">
            <a-input
              v-decorator="['BmwAppId']"
              :placeholder="$t('user.v142')"
              :disabled="mode === 3"
            />
          </a-form-item>
          <a-form-item label="Department APP ID">
            <a-input
              v-decorator="['BbaAppId']"
              :placeholder="$t('user.v143')"
              :disabled="mode === 3"
            />
          </a-form-item>
          <a-form-item label="Feature ID">
            <a-input
              v-decorator="['FeatherId']"
              :placeholder="$t('user.v144')"
              :disabled="mode === 3"
            />
          </a-form-item>
        </div>
        <a-form-item :label="$t('menu.exception.not-permission')">
          <a-textarea
            v-decorator="['appRemarks']"
            :placeholder="$t('user.verification-code.required1115661812233')"
            :rows="4"
            :disabled="mode === 3"
          />
        </a-form-item>
        <a-form-item label="ID" v-if="mode == 1" class="hidden">
          <a-input v-decorator="['id']" :disabled="mode === 3" />
        </a-form-item>
      </a-form>
      <div
        class="absolute right-0 bottom-0 w-full px-4 py-[10px] bg-white text-left z-1 flex justify-center"
        v-if="mode !== 3"
      >
        <a-row class="w-full" :gutter="24">
          <a-col :span="12">
            <a-button
              class="w-full border-none hover:bg-[#3F8CFF] hover:bg-opacity-5 shadow"
              @click="close"
              >{{ $t("app.setting.themecolor.rr") }}</a-button
            >
          </a-col>
          <a-col :span="12">
            <a-button
              :loading="loading"
              class="w-full border-none shadow"
              type="primary"
              @click.native.prevent="submit()"
            >
              <span v-if="!loading">{{ $t("app.setting.themecolor.ss") }}</span>
              <span v-else>{{ $t("app.setting.themecolor.tt") }}...</span>
            </a-button>
          </a-col>
        </a-row>
      </div>
    </a-modal>
  </div>
</template>

<script>
import { appIdCreate, appIdChange, appIdDetailList } from "@/api/appid";
import { getUserList, userQuery, userQuery1 } from "@/api/common/form";
import tableSelect from "@/components/tableSelect/tableSelect.vue";

export default {
  components: { tableSelect },
  data() {
    return {
      // 下面这些都是通用的
      form: this.$form.createForm(this),
      visible: false,
      disabled: false,
      loading: false,
      userList: [],
      appList: [],
      // 这个要根据服务修改title
      // titleMap: ['新建数据盘库', '修改数据盘库'],
      titleMap: "",
      timerId: "",
      keyword: "",
      inputValue: "",
      inputValue1: "",
      ModalText: "Content of the modal",
      confirmLoading: false,
      ifflag: null,
      ifPop: true,
      ifModal: false,
      mode: -1,
    };
  },
  mounted() {},
  watch: {
    async inputValue(value) {
      const { data } = await getUserList({
        UserEmail: value,
        UserName: value,
      });
      this.userList = data;
    },
    async inputValue1(value) {
      const { data } = await userQuery1({
        YtAdminDepartment: value,
        types: 2,
      });
      this.appList = data;
    },
  },
  methods: {
    /**
     *
     * @param {*} type 0 新增 1 修改
     * @param {*} data 列表传过来的值
     */
    // 联系人查询async
    async filte1rOption(value) {
      // this.inputValue = value;
      const { data } = await getUserList({
        UserEmail: value,
        UserName: value,
      });
      this.userList = data;
    },
    async filte1rOption1(value) {
      // this.inputValue1 = value;
      const { data } = await userQuery1({
        YtAdminDepartment: value,
        types: 2,
      });
      this.appList = data;
    },
    async open(mode = 0, data = {}, ifPop, ifModal) {
      this.mode = mode;
      this.ifPop = ifPop;
      this.form.resetFields();
      this.ifflag = 0;
      this.titleMap = this.$t("user.11");
      this.visible = true;
      this.ifModal = ifModal;
      // 获取用户列表下拉
      // const { data: userList } = await userQuery(1);
      // this.userList = userList
      // 获取App所属部门下拉
      const { data: appList } = await userQuery(2);
      // console.log("appList", appList);
      this.appList = appList;
      // 如果是修改
      if (mode !== 0) {
        this.titleMap = this.$t(mode === 1 ? "user.2222" : "user.222222");
        let { data: appDetail } = await appIdDetailList({ Id: data.Id });
        //修改的时候需要给form赋值
        if (appDetail.AppSource === 1) {
          this.ifflag = 1;
        }
        await this.$nextTick();
        this.form.setFieldsValue({
          appSource: appDetail.AppSource,
          appType: appDetail.AppType + "",
          appName: data.AppName,
          appOwner: data.AppOwner,
          appDepartment: data.AppDepartment,
          appRemarks: appDetail.AppRemarks,
          id: data.Id,
          FeatherId: data.FeatherId,
          BmwAppId: appDetail.BmwAppId,
          BbaAppId: appDetail.BbaAppId,
        });
      }
    },
    // 提交 通用的
    submit() {
      const {
        form: { validateFields },
      } = this;
      // 按钮loading
      this.loading = true;
      // validateFields 是校验form表单数据
      // force: true 是默认所有字段都校验
      // values 表单的值
      validateFields({ force: true }, async (err, values) => {
        if (!err) {
          try {
            const params = { ...values };
            // 判断状态是新增还是修改 调用不同的api
            params.appOwner = params.appOwner.replaceAll("/", "#@%$");
            if (this.mode == 0) {
              const { data: project } = await appIdCreate({ ...params });
              //   console.log(project);
              this.sendDataToParent(project);
            } else {
              const { data: project } = await appIdChange({ ...params });
              //   console.log(project);
              this.sendDataToParent(project);
            }
            // 如果成功就调用父页面当前组件的succeed上绑定的事件
            this.$message.success(
              this.$t("user.verification-code.required111566110577308")
            );
            //如果成功就关闭
            this.close();
            const h = this.$createElement;
            let lang = localStorage.getItem("lang");
            if (this.mode !== 1 && this.ifPop) {
              this.$info({
                content: h(
                  "div",
                  {},
                  lang === '"zh-CN"'
                    ? [
                        h("span", "应用已新增，可在"),
                        h("span", { class: "blue-content" }, "应用管理"),
                        h("span", "中查看和编辑"),
                        h("br"),
                        h("span", "如有任何问题，请联系"),
                        h(
                          "span",
                          { class: "blue-content" },
                          "China-DG@enterprise.com"
                        ),
                      ]
                    : [
                        h(
                          "span",
                          "The APP has been added and can be viewed and edited in "
                        ),
                        h("span", { class: "blue-content" }, "APP Management"),
                        h("br"),
                        h("span", "If you have any questions, please contact "),
                        h(
                          "span",
                          { class: "blue-content" },
                          "China-DG@enterprise.com"
                        ),
                      ]
                ),
                okText: lang === '"zh-CN"' ? "关闭" : "close",
                class: "add-app-model",
              });
            }
          } catch (error) {
            console.log("err", error);
            this.$message.error(
              this.$t(
                "user.verification-code.required111566110577371442281431777"
              )
            );
          } finally {
            this.loading = false;
          }
        } else {
          setTimeout(() => {
            this.loading = false;
          }, 600);
        }
      });
    },
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text
          .toLowerCase()
          .indexOf(input.toLowerCase()) >= 0
      );
    },
    // 关闭 通用的
    close() {
      // 修改侧边栏状态
      this.visible = false;
      // 清空form的值
      this.form.resetFields();
    },
    sendDataToParent(e) {
      // 通过$emit触发自定义事件，并将数据作为参数传递
      this.$emit("child-event", e, this.ifModal);
      this.$emit("getList");
    },
    handleCancel(e) {
      console.log("Clicked cancel button");
      this.visible = false;
    },
    ownerChange() {
      this.form.setFieldsValue({
        appDepartment: this.form.getFieldValue("appOwner").split("/")[1],
      });
    },
  },
};
</script>
<style lang="less">
.add-app-model {
  .anticon-info-circle {
    display: none;
  }
  .blue-content {
    color: #1940b4;
  }
  .ant-modal-confirm-btns {
    float: initial;
    display: flex;
    justify-content: center;
  }
}
</style>